<?php
namespace Tools\Number;

/**
 * 随机生成器
 * Class RandomTool
 */
class RandomTool
{

    const TYPE_STR = 'string';

    const TYPE_INT = 'int';

    public static function random(int $len = 0, $type = self::TYPE_STR)
    {
        switch (strtolower($type)){
            case self::TYPE_INT :
//                return self::randomNumbser($len);
            default:
                return self::randomChars($len);
        }
    }

    /**
     * 随机字符串
     * @param int $length
     * @return string
     * @author KQ
     */
    public static function randomChars(int $length = 8): string
    {
        // 字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        if($length > strlen($chars)){
            $chars = str_pad($chars, $length, $chars, STR_PAD_BOTH);
        }
        $chars = str_shuffle($chars);

        return substr(str_shuffle($chars),mt_rand(0,strlen($chars) - $length),$length);
    }

    /**
     * 随机数字
     * @param int $length
     * @return bool|string
     */
    public static function randomNumber(int $length = 8)
    {
        //生成一个数字数组
        for ($i = 100; $i <= 999; $i++) $chars[] = $i;
        // 在 $chars 中随机取 $length 个数组元素键名
        $keys = array_rand($chars,$length);
        shuffle($keys);
        $str = '';
        for($i = 0; $i < $length; $i++){
            // 将 $length 个数组元素连接成字符串
            $str .= $chars[$keys[$i]];
        }
        $random = date("YmdHis"). rand(100000, 999999) . date("YmdHis") . $str;
        return substr(str_shuffle($random), 0, $length);
    }

    /**
     * 生成随机字符串 可用于生成随机密码等
     * @param int $length 生成长度
     * @param string $alphabet 自定义生成字符集
     * @return bool|string
     */
    public static function character(int $length = 6, string $alphabet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789')
    {
        if ($length >= strlen($alphabet)) {
            $rate = intval($length / strlen($alphabet)) + 1;
            $alphabet = str_repeat($alphabet, $rate);
        }
        return substr(str_shuffle($alphabet), 0, $length);
    }

    /**
     * 生成随机数字 可用于生成随机验证码等
     * @param int $length 生成长度
     * @return bool|string
     */
    public static function number(int $length = 6)
    {
        return static::character($length, '0123456789');
    }

    /**
     * 数组随机抽出一个
     * @param array $arr
     * @return mixed|null
     */
    public static function arrayRandOne(array $arr)
    {
        if (empty($arr)) return null;
        return $arr[array_rand($arr)];
    }
}